﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HexagonWeb.BIL;
using HexagonWeb.Common;
using HexagonWeb.IBIL;
using HexagonWeb.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;

namespace HexagonWeb.Controllers
{
    public class UserController : Controller
    {
        private InterfaceUserService userService;

        private InterfaceTicketService ticketService;

        private InterfaceAirlineService airlineService;

        private InterfaceSeatService seatService;

        #region 属性
        private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }
        #endregion

        public UserController()
        {
            userService = new UserService();
            ticketService = new TicketService();
            airlineService = new AirlineService();
            seatService = new SeatService();
        }

        private MessageDbContext db = new MessageDbContext();

        // GET: Messages
        public ActionResult MessageIndex()
        {
            return View(db.Messages.ToList());
        }


        // GET: User
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login(string returnUrl)
        {
            return View();
        }


        public ActionResult Register()
        {
            return View();
        }

        //注销
        public ActionResult Logout()
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return Redirect(Url.Content("~/"));
        }

        //个人资料
        public ActionResult Info()
        {
            return View();
        }

        //显示资料
        public ActionResult Details()
        {
            return View(userService.Find(User.Identity.Name));
        }

        //更改密码视图
        public ActionResult ChangePassword()
        {
            return View();
        }


        //验证码
        public ActionResult VerificationCode()
        {
            string verificationCode = Security.CreateVerificationText(6);
            Bitmap _img = Security.CreateVerificationImage(verificationCode, 160, 30);
            _img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            TempData["VerificationCode"] = verificationCode.ToUpper();
            return null;
        }

        //用来处理登录
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Login(LoginViewModel loginViewModel)
        {
            if (ModelState.IsValid)
            {
                var _user = userService.Find(loginViewModel.UserName);
                if (_user == null)
                    ModelState.AddModelError("UserName", "用户名不存在");
                else if (_user.Password == loginViewModel.Password)
                {
                    var _identity = userService.CreateIdentity(_user, DefaultAuthenticationTypes.ApplicationCookie);
                    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = loginViewModel.RememberMe }, _identity);
                    Session["ID"] = _user.ID;
                    return RedirectToAction("Today", "Airline");
                }
                else
                    ModelState.AddModelError("Password", "密码错误");
            }
            return View();
        }


        //用来处理用户注册提交的数据
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterViewModel register)
        {
            if(TempData["VerificationCode"] == null || TempData["VerificationCode"].ToString() !=
                register.VerificationCode.ToUpper())
            {
                ModelState.AddModelError("VerificationCode", "验证码错误");
                return View(register);
            }
            if(ModelState.IsValid)
            {
                if (userService.Exist(register.UserName))
                    ModelState.AddModelError("UserName", "用户名已存在");
                else
                {
                    User _user = new User()
                    {
                        UserName = register.UserName,
                        Password = register.Password,
                        Option = register.Option,
                        Service = register.Service
                    };
                    _user = userService.Add(_user);
                    if(_user.ID > 0)
                    {
                        var _identity = userService.CreateIdentity(_user, DefaultAuthenticationTypes.ApplicationCookie);
                        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                        AuthenticationManager.SignIn(_identity);
                        return RedirectToAction("Login", "User");
                    }
                    else{
                        ModelState.AddModelError("", "注册失败");
                    }
                }
            }
            return View(register);
        }




        //修改资料
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Modify()
        {
            var _user = userService.Find(User.Identity.Name);
            if (_user == null)
                ModelState.AddModelError("", "用户不存在");
            else
            {
                if(TryUpdateModel(_user, new string[]{"Option", "Service"}))
                {
                    if (ModelState.IsValid)
                    {
                        if (userService.Update(_user))
                            ModelState.AddModelError("", "修改成功！");
                        else
                            ModelState.AddModelError("", "无需要修改的资料");
                    }
                    else
                        ModelState.AddModelError("", "更新失败");
                }
            }
            return View("Details", _user);
        }

        //修改密码
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordViewModel passwordModel)
        {
            if(ModelState.IsValid)
            {
                var _user = userService.Find(User.Identity.Name);
                if (_user.Password == passwordModel.OriginalPassword)
                {
                    _user.Password = passwordModel.Password;
                    if (userService.Update(_user))
                    {
                        ModelState.AddModelError("", "修改密码成功");
                    }
                    else
                        ModelState.AddModelError("", "修改密码失败");
                }
                else
                    ModelState.AddModelError("", "原密码错误");
            }
            return View(passwordModel);
        }

        //查询订票
        public ActionResult TicketDetail()
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("/User/Login");
                return View();
            }
            var _user = userService.Find(User.Identity.Name);
            int record;
            IQueryable<Ticket> _tickets = ticketService.FindByUserID(_user.ID, 1, 10, out record, 0);
            return View(_tickets);
            //List<SeatViewModel> _viewModels = new List<SeatViewModel>();
            //foreach (var item in _tickets){
            //    if (item == null)
            //    {
            //        return View();
            //    }
            //    System.Diagnostics.Debug.Print("!!!!!!!!!!!!!!!!!!! {0}", item.AirlineID);
            //    Airline _airline = airlineService.Find(item.AirlineID);
            //    var _seatViewModel = new SeatViewModel()
            //    {
            //        PNR = item.PNR,
            //        Level = item.Level,
            //        Column = item.Column,
            //        Row = item.Row,
            //        Type = _airline.Type
            //    };
            //    if (item.Level == 0)
            //        _seatViewModel.Cost = _airline.LowCost;
            //    if (item.Level == 1)
            //        _seatViewModel.Cost = _airline.MidCost;
            //    if (item.Level == 2)
            //        _seatViewModel.Cost = _airline.TopCost;
            //    _viewModels.Add(_seatViewModel);
            //}
            //return View(_viewModels.ToList());
        }
        
        //取消订票
        public ActionResult TicketCancel(string PNR)
        {
            var _ticket = ticketService.Find(PNR);
            var _seat = seatService.Find(_ticket.AirlineID);
            if (_ticket.Level == 0)
                _seat.LowNum -= 1;
            if (_ticket.Level == 1)
                _seat.MidNum -= 1;
            if (_ticket.Level == 2)
                _seat.TopNum -= 1;
            seatService.Update(_seat);
            ticketService.Delete(_ticket);

            var _user = userService.Find(User.Identity.Name);
            int record;
            IQueryable<Ticket> _tickets = ticketService.FindByUserID(_user.ID, 1, 10, out record, 0);
            return View("TicketDetail",_tickets);
        }
    }
}